package com.dwxt.cdms.controller.base;

import com.alibaba.fastjson.JSONObject;
import com.dwxt.common.base.BaseResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

/**
 * 各种测试
 *
 * @author Kuang.JiaZhuo
 * @date 2020-09-09 17:28
 */
@RestController
@RequestMapping({ "/cdms/test" })
public class TestController {
    /**
     * 接收流信息
     *
     * @param request
     * @return
     */
    @PostMapping("/receiveStream1")
    public String receiveStream1(HttpServletRequest request) {
        String result = "";
        System.out.println("进来了");
        try {
            //获取request里的所有部分
            Collection<Part> parts = request.getParts();
            for (Iterator<Part> iterator = parts.iterator(); iterator.hasNext(); ) {
                Part part = iterator.next();
                System.out.println("名称========" + part.getName());
                if ("JsonObj".equals(part.getName())) {
                    //解析json对象
                    BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream()));
                    String line = "";
                    String parseString = "";
                    while ((line = reader.readLine()) != null) {
                        parseString += line;
                    }
                    JSONObject json = JSONObject.parseObject(parseString);
                    System.out.println("接收到的json对象为=====" + json.toJSONString());
                } else if ("File".equals(part.getName())) {
                    String fileName = "";
                    Long size = part.getSize();
                    //文件名的获取，可以直接获取header里定义好的FIleName（大部分没有），或从Content-Disposition去剪切出来
//                    String head = part.getHeader("Content-Disposition");
//                    fileName = head.substring(head.indexOf("filename=")+ 10, head.lastIndexOf("\""));
                    fileName = part.getHeader("FileName");
                    System.out.println(fileName + size);
//                    //这里就是文件，文件流就可以直接写入到文件了
//                    InputStream inputStream = part.getInputStream();
//                    OutputStream outputStream = new FileOutputStream(fileName);
//                    int bytesWritten = 0;
//                    int byteCount = 0;
//                    byte[] bytes = new byte[1024];
//                    while ((byteCount = inputStream.read(bytes)) != -1) {
//                        outputStream.write(bytes, bytesWritten, byteCount);
//                        bytesWritten += byteCount;
//                    }
//                    inputStream.close();
//                    outputStream.close();
                }
            }

            //如果嫌上面获取文件的麻烦，用下面这个比较简单，解析成multipartFile
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //统计文件数
            Integer fileCount = 0;
            //请求里key为File的元素（即文件元素）
            List<MultipartFile> list = multiRequest.getFiles("File");
            while (fileCount < list.size()) {
                MultipartFile file = list.get(fileCount);
                System.out.println(file.getName());
                System.out.println(file.getOriginalFilename());
                System.out.println(file.getSize());
                fileCount++;
            }
            System.out.println("共有" + fileCount + "个文件");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @方法名：receiveStream12
     * @描述： 转发测试
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2020/9/17 0:25
     */
    @RequestMapping("/receiveStream2")
    public BaseResult receiveStream12(HttpServletRequest request) {
        JSONObject resultStr = request2JO(request);
        Map<String,Object> map = new HashMap<>();
        map.put("requestURI",request.getRequestURI());
        map.put("queryString",request.getQueryString());
        map.put("remoteHost",request.getRemoteHost());
        map.put("remoteAddr",request.getRemoteAddr());
        map.put("pathInfo",request.getPathInfo());
        map.put("remotePort",request.getRemotePort());
        map.put("localAddr",request.getLocalAddr());
        map.put("localName",request.getLocalName());
        map.put("serverPort",request.getServerPort());
        map.put("servletPath",request.getServletPath());
        map.put("authType",request.getAuthType());
        map.put("contextPath",request.getContextPath());
        map.put("serverName",request.getServerName());
        map.put("requestURL",request.getRequestURL().toString());
        map.put("resultStr",resultStr);
        RestTemplate restTemplate = new RestTemplate();
        BaseResult baseResult = restTemplate.postForObject("http://118.178.180.213:9124/cdms/parse/receiveData", resultStr, BaseResult.class);
        return baseResult;
    }

    /**
     * @方法名：request2JO
     * @描述： 取出request的消息体
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2020/9/17 0:24
     */
    public JSONObject request2JO(HttpServletRequest request){
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String line = null;
        StringBuilder sb = new StringBuilder();
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String bodyStr = sb.toString();
        JSONObject resultStr = (JSONObject) JSONObject.parse(bodyStr);
        return resultStr;
    }


}
